package week_eight;

import java.util.ArrayList;
import java.util.List;

public class ReverseWordsInAString_151 {
    public String reverseWords(String s) {
        List<String> list = new ArrayList<>();

        int n = s.length();
        int start = 0;
        int end = 0;

        while (end < n) {
            while (end < n && s.charAt(end) == ' ') end++;
            start = end;
            while (end < n && s.charAt(end) != ' ') end++;
            if (start != end)
                list.add(s.substring(start, end));
        }

        StringBuilder sb = new StringBuilder();

        for (int i = list.size() - 1; i > 0; i--) {
            // System.out.println(i+" : "+list.get(i));
            sb.append(list.get(i)).append(" ");
        }
        sb.append(list.get(0));

        return sb.toString();

    }
}
